require 'check_quantity_callback'
include ImagePath

class Material < ActiveRecord::Base
  belongs_to :style
  has_many :products,:dependent=>:delete_all
  before_save :convert_size_array,CheckQuantityCallback.new(:quantity)
  attr_accessor :size_array
  validates_numericality_of :quantity
  file_column :image_url, :magick => {:geometry=>"450X450",
    :versions => { "thumb" => "90X90","medium" => "200X200","li"=>"130X130","origin"=>"800X800"}
  }
  file_column :back_image_url, :magick => {:geometry=>"450X450",
    :versions => { "thumb" => "90X90","medium" => "200X200"}
  }

  file_column :detail_image_url1, :magick => {:geometry=>"200X200"}
  file_column :detail_image_url2, :magick => {:geometry=>"200X200"}

  SIZES = [
    [ "XXL",   "XXL" ],
    [ "XL",    "XL"  ],
    [ "L",     "L"   ],
    [ "M",     "M"   ],
    [ "S",     "S"   ],
  ]


  def back_image_path
    "/material/back_image_url/" +  self.back_image_url_relative_path if self.back_image_url
  end

  def self.create_new_size(dir,size)
    self.find(:all).each do |m|
      file_name = File.basename(m.image_url)
      new_dir = File.dirname(m.image_url) + "/" + dir

      img = ImageList.new(m.image_url)
      img.resize_to_fit!(size)

      Dir.mkdir( new_dir,0775) if !File.exist?( new_dir)
      img.write(new_dir + "/" +file_name)

    end
  end

  def self.find_by_sex(sex,limit)
    Material.find_by_sql(["select * from styles s,materials m
      where s.id = m.style_id and s.sex = ? and m.active = 1 and s.active = 1 order by m.id desc limit ?",sex,limit])
  end

  private
  def convert_size_array
    return if !size_array

    tmp_array = []
    size_array.values.each do |i|
      tmp_array << i if i!="0"
    end
    self.tee_size = tmp_array.join(",")
  end

  def check_quantity
    return self.quantity !=0
    self.active = UNACTIVE
  end
end
